package com.hangxin.basic.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 控制用户操作步骤
 * 
 * @author ljl
 * @since 2017-03-24
 */
public class StepFilter extends HandlerInterceptorAdapter {
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String url = request.getRequestURL().toString();
		
		HttpSession session = request.getSession();
		
		 // 登陆url
		String indexUrl = url.substring(0, url.lastIndexOf("/"));

		//错误导航
		String errorUrl = url.substring(0, url.lastIndexOf("/"))+"/errorUI.do";
		
        String path = url.substring(url.lastIndexOf("/"));

        // 超时处理，ajax请求超时设置超时状态，页面请求超时则返回提示并重定向
        if (path.indexOf(".do") != -1&&path.indexOf("errorUI.do") ==-1
                && session.getAttribute("valid") == null) {

            // 判断是否为ajax请求
            if (request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with")
                    .equalsIgnoreCase("XMLHttpRequest")) {


				response.sendRedirect(errorUrl);

                return false;

            } else {

                String str = "<script language='javascript'>alert('会话过期，请您重新投保！');"

                        + "window.top.location.href='"

                        + indexUrl

                        + "';</script>";

                response.setContentType("text/html;charset=UTF-8");// 解决中文乱码

                try {

                    PrintWriter writer = response.getWriter();

                    writer.write(str);

                    writer.flush();

                    writer.close();
                    
                    return false;

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }
            
        }

		// 如果用户 访问第二步
		if (url.indexOf("secondStep.do") != -1) {

			// 是否通过第一步
			if (StepSessionUtil.passFirstStep(request)) {
				return true;
			} else {
//				url = url.substring(0, url.lastIndexOf("/"));
//				response.sendRedirect(url);
//				return false;
			}
		}

		// 如果用户 访问第三步
		if (url.indexOf("thirdStep.do") != -1) {

			// 是否通过第二步
			if (StepSessionUtil.passSecondStep(request)) {

				return true;

			} else {
//				url = url.substring(0, url.lastIndexOf("/"));
//				response.sendRedirect(url);
//				return false;
			}
		}

		// 如果用户 访问第四步
		if (url.indexOf("fourthStep.do") != -1) {

			// 是否通过第三步
			if (StepSessionUtil.passThirdStep(request)) {

				return true;

			} else {
//				url = url.substring(0, url.lastIndexOf("/"));
//				response.sendRedirect(url);
//				return false;
			}
		}

		return true;
	}

}
